from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Admin
from api.models import *
from api.utils import *


# Create your views here.
def login(request):
    if request.method == "POST":
        username = request.POST["username"]
        password = request.POST["password"]
        admin = Admin.objects.get(pk=1)
        if username == admin.username and password == admin.password:
            request.session["user"] = "admin"
            request.session.set_expiry(0)
            return HttpResponseRedirect("../index")
        else:
            return render(request, "login.html", {"error": 1})
    else:
        return render(request, "login.html", {"error": 0})


def index(request):
    if "user" not in request.session.keys():
        return HttpResponseRedirect("../login")
    if request.session["user"] != "admin":
        return HttpResponseRedirect("../login")
    return render(request, "index.html")


def funds(request):
    if "user" not in request.session.keys():
        return HttpResponseRedirect("../login")
    if request.session["user"] != "admin":
        return HttpResponseRedirect("../login")
    funds = []
    page = 1

    if "page" not in request.GET.keys():
        page = 1
        funds = Fund.objects.all()
        funds = funds[0:20]
    else:
        page = request.GET["page"]
        page = eval(page)
        funds = Fund.objects.all()
        funds = funds[(page - 1) * 20: page * 20]

    context = []
    for fund in funds:
        context.append([fund.fund_id, fund.fund_name, fund.price, fund.manager, fund.category])

    max_page = 0
    max_len = len(Fund.objects.all())
    if max_len % 20 == 0:
        max_page = int(max_len / 20)
    else:
        max_page = int(max_len / 20) + 1

    return render(request, 'funds.html', {"context": context, "page": page, "search": 0, "max": max_page})


def fund_detail(request):
    if "user" not in request.session.keys():
        return HttpResponseRedirect("../login")
    if request.session["user"] != "admin":
        return HttpResponseRedirect("../login")
    fund_id = request.GET["id"]
    fund = Fund.objects.get(fund_id=fund_id)
    price = []
    date = []
    for data in get_many_price_by_id(fund_id, 20):
        price.append(float(data[1]))
        date.append(data[0])
    print(price)
    print(date)
    return render(request, 'fund-detail.html', {"fund": fund, "price": price, "date": date})


def delete(request):
    if "user" not in request.session.keys():
        return HttpResponseRedirect("../login")
    if request.session["user"] != "admin":
        return HttpResponseRedirect("../login")
    fund_id = request.GET["id"]
    fund = Fund.objects.get(fund_id=fund_id)
    varies = Vary.objects.filter(fund_id=fund_id)
    fund.delete()
    for vary in varies:
        vary.delete()
    positions = Position.objects.filter(fund_id=fund_id)
    for position in positions:
        position.delete()
    follows = Follow.objects.filter(fund_id=fund_id)
    for follow in follows:
        follow.delete()
    timing = Timing.objects.filter(fund_id=fund_id)
    for t in timing:
        t.delete()
    holds = Hold.objects.filter(fund_id=fund_id)
    for hold in holds:
        hold.delete()
    queues = Queue.objects.filter(fund_id=fund_id)
    for queue in queues:
        queue.delete()
    checks = Check.objects.filter(fund_id=fund_id)
    for check in checks:
        check.delete()
    sizes = Size.objects.filter(fund_id=fund_id)
    for size in sizes:
        size.delete()
    rates = Rate.objects.filter(fund_id=fund_id)
    for rate in rates:
        rate.delete()
    clicks = Click.objects.filter(fund_id=fund_id)
    for click in clicks:
        click.delete()
    fund_vectors = FundVector.objects.filter(fund_id=fund_id)
    for fund_vector in fund_vectors:
        fund_vector.delete()
    user_fund_scores = UserFundScore.objects.filter(fund_id=fund_id)
    for user_fund_score in user_fund_scores:
        user_fund_score.delete()
    return HttpResponseRedirect("../funds")


def modify(request):
    if "user" not in request.session.keys():
        return HttpResponseRedirect("../login")
    if request.session["user"] != "admin":
        return HttpResponseRedirect("../login")
    fund_id = request.GET["fundId"]
    fund = Fund.objects.get(fund_id=fund_id)
    type = request.GET["type"]
    if type == "1":
        fund.manager = request.GET["manager"]
    elif type == "2":
        fund.buy_min = request.GET["buyMin"]
    elif type == "3":
        fund.buy_source_rate = request.GET["buySourceRate"]
    elif type == "4":
        fund.buy_rate = request.GET["buyRate"]
    elif type == "5":
        fund.day_growth = request.GET["dayGrowth"]
    elif type == "6":
        fund.week_growth = request.GET["weekGrowth"]
    else:
        fund.month_growth = request.GET["monthGrowth"]
    fund.save()
    return HttpResponseRedirect("../fund-detail?id=" + fund_id)


def logout(request):
    del request.session["user"]
    return HttpResponseRedirect("../login")


def users(request):
    if "user" not in request.session.keys():
        return HttpResponseRedirect("../login")
    if request.session["user"] != "admin":
        return HttpResponseRedirect("../login")
    users = User.objects.all()
    if "openid" in request.GET:
        openid = request.GET["openid"]
        users = User.objects.filter(openid=openid)
        context = []
        for user in users:
            tmp = [user.openid, user.username, user.money, user.reg_time, user.instruction]
            context.append(tmp)
        users = User.objects.filter(username=openid)
        for user in users:
            tmp = [user.openid, user.username, user.money, user.reg_time, user.instruction]
            context.append(tmp)
        return render(request, "users.html", {"users": context})
    context = []
    for user in users:
        tmp = [user.openid, user.username, user.money, user.reg_time, user.instruction]
        context.append(tmp)
    return render(request, "users.html", {"users": context})


def jump(request):
    return HttpResponseRedirect("administrator/login")


def chart(request):
    if "user" not in request.session.keys():
        return HttpResponseRedirect("../login")
    if request.session["user"] != "admin":
        return HttpResponseRedirect("../login")
    # 关注基金统计
    follow_chart = dict()
    for i in range(1, 6):
        follow_chart[i] = 0
    for follow in Follow.objects.all():
        fund = Fund.objects.get(fund_id=follow.fund_id)
        follow_chart[fund.category] += 1

    # 持有基金统计
    hold_chart = dict()
    for i in range(1, 6):
        hold_chart[i] = 0
    for hold in Hold.objects.all():
        fund = Fund.objects.get(fund_id=hold.fund_id)
        hold_chart[fund.category] += 1

    # 基金涨幅统计
    increase_chart = dict()
    cnt = dict()
    for fund in Fund.objects.all():
        if fund.category not in increase_chart.keys():
            increase_chart[fund.category] = fund.day_growth
            cnt[fund.category] = 1
        else:
            increase_chart[fund.category] += fund.day_growth
            cnt[fund.category] += 1
    for key in increase_chart.keys():
        increase_chart[key] /= cnt[key]

    res = dict()
    res["increase"] = increase_chart
    res["follow"] = follow_chart
    res["hold"] = hold_chart
    return render(request, 'chart.html', res)


def search(request):
    if "user" not in request.session.keys():
        return HttpResponseRedirect("../login")
    if request.session["user"] != "admin":
        return HttpResponseRedirect("../login")
    if "fund" in request.GET and len(request.GET["fund"]) != 0:
        search_info = request.GET["fund"]
        if ord('0') <= ord(search_info[0]) <= ord('9'):  # 数字
            if len(search_info) < 6:
                tmp = "0" * (6 - len(search_info))
                search_info = tmp + search_info
            funds = dict()
            for fund in Fund.objects.all():
                funds[fund.fund_id] = 0
                cnt = 0
                for char in fund.fund_id:
                    if cnt >= len(search_info):
                        break
                    if char == search_info[cnt]:
                        cnt += 1
                funds[fund.fund_id] += cnt
            cnt = 0
            funds_id = []
            for i in reversed(sorted(funds.items(), key=lambda kv: (kv[1], kv[0]))):
                funds_id.append(i[0])
                cnt += 1
                if cnt == 10:
                    break
            data = []
            for fund_id in funds_id:
                fund = Fund.objects.get(fund_id=fund_id)
                data.append([fund.fund_id, fund.fund_name, fund.price, fund.manager, fund.category])
            return render(request, "funds.html", {"context": data, "search": 1})
        else:  # 字母 / 汉字
            funds = dict()
            for fund in Fund.objects.all():
                funds[fund.fund_name] = 0
                cnt = 0
                for char in fund.fund_name:
                    if cnt >= len(search_info):
                        break
                    if char == search_info[cnt]:
                        cnt += 1
                funds[fund.fund_name] += cnt
            cnt = 0
            funds_name = []
            for i in reversed(sorted(funds.items(), key=lambda kv: (kv[1], kv[0]))):
                funds_name.append(i[0])
                cnt += 1
                if cnt == 10:
                    break
            data = []
            for fund_name in funds_name:
                fund = Fund.objects.get(fund_name=fund_name)
                data.append([fund.fund_id, fund.fund_name, fund.price, fund.manager, fund.category])
            return render(request, "funds.html", {"context": data, "search": 1})
    else:
        user_id = request.GET["user"]
        users = User.objects.filter(openid=user_id)
        if "openid" in request.GET:
            openid = request.GET["openid"]
            users = User.objects.filter(openid=openid)
            context = []
            for user in users:
                tmp = [user.openid, user.username, user.money, user.reg_time, user.instruction]
                context.append(tmp)
            users = User.objects.filter(username=openid)
            for user in users:
                tmp = [user.openid, user.username, user.money, user.reg_time, user.instruction]
                context.append(tmp)
            return render(request, "users.html", {"users": context})
        context = []
        for user in users:
            tmp = [user.openid, user.username, user.money, user.reg_time, user.instruction]
            context.append(tmp)
        users = User.objects.filter(username=user_id)
        for user in users:
            tmp = [user.openid, user.username, user.money, user.reg_time, user.instruction]
            context.append(tmp)
        return render(request, "users.html", {"users": context})
